//
//  SUIColor.swift
//  niuguwang
//
//  Created by BrightLi on 2021/2/26.
//  Copyright © 2021年 taojinzhe. All rights reserved.
//

import Foundation
import UIKit
import MJRefresh
import SDWebImage


public let NavRect = CGRect(x:0,y:0,width:ScreenWidth,height:TopBarHeight)

@objcMembers public class SUIUtil:NSObject
{
    dynamic public class func imageOfView(_ view:UIView?)->UIImage?
    {
        if view == nil{
            return nil
        }
        view?.layoutIfNeeded()
        if view!.frame.size.width<=0 || view!.frame.size.height<=0{
            return nil
        }
        var image:UIImage?
        UIGraphicsBeginImageContextWithOptions(view!.frame.size, false, 0.0)
        view!.layer.render(in: UIGraphicsGetCurrentContext()!)
        image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
    dynamic public class func imageOfColor(_ color:UIColor) -> UIImage!
    {
        let size = CGSize(width: 1, height: 1)
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let ctx = UIGraphicsGetCurrentContext()!
        ctx.setFillColor(color.cgColor)
        ctx.fill(rect)
        let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
    dynamic public class func imageOfColor(_ hexColor:UInt32,alpha:CGFloat) -> UIImage!
    {
        let fillColor = SUIUtil.colorOf(hexColor, alpha: alpha)
        return imageOfColor(fillColor)
    }
    // 设置图片
    dynamic public class func setImage(_ imageView:UIImageView?,url:String?)
    {
        setImage(imageView, url: url, placeholder: "", completed: nil)
    }
    // 设置图片
    dynamic public class func setImage(_ imageView:UIImageView?,url:String?,placeholder:String)
    {
        setImage(imageView, url: url, placeholder: placeholder, completed: nil)
    }
    // 设置图片
    dynamic public class func setImage(_ imageView:UIImageView?,url:String?,placeholder:String="",completed:SDExternalCompletionBlock?)
    {
        if imageView == nil{
            return
        }
        var holder:UIImage?
        if placeholder.count>0{
            holder=UIImage(named: placeholder)
        }
        if url == nil || url!.count<1 || !SDataUtil.isImgURL(url!){
            if holder != nil{
                imageView!.image=holder!
            }else{
                imageView!.image=nil
            }
            return
        }
        guard let path=URL(string:url!) else{
            if holder != nil{
                imageView!.image=holder!
            }
            return
        }
        imageView!.sd_setImage(with: path, placeholderImage: holder, options: [.retryFailed,.allowInvalidSSLCertificates],completed:completed)
    }
    
    // 渐变
    dynamic public class func gradient(_ target:UIView,beginColor:UIColor,endColor:UIColor)
    {
        var find=false
        var gradientLayer:CAGradientLayer?
        if let sublayers = target.layer.sublayers{
            for layer in sublayers{
                if let temp=layer as? CAGradientLayer{
                    gradientLayer = temp
                    find=true
                    break
                }
            }
        }
        if gradientLayer == nil{
            gradientLayer = CAGradientLayer()
        }
        gradientLayer!.frame = target.bounds
        gradientLayer!.startPoint = CGPoint(x:0.5,y:0)
        gradientLayer!.endPoint = CGPoint(x:0.5,y:1)
        let fromColor = beginColor.cgColor
        let toColor = endColor.cgColor
        gradientLayer!.colors = [fromColor,toColor]
        if !find{
            target.layer.addSublayer(gradientLayer!)
        }
    }
    
    // 渐变
    dynamic public class func gradientLeftToRight(_ target:UIView,beginColor:UIColor,endColor:UIColor)
    {
        var find=false
        var gradientLayer:CAGradientLayer?
        if let sublayers = target.layer.sublayers{
            for layer in sublayers{
                if let temp=layer as? CAGradientLayer{
                    gradientLayer = temp
                    find=true
                    break
                }
            }
        }
        if gradientLayer == nil{
            gradientLayer = CAGradientLayer()
        }
        gradientLayer!.frame = target.bounds
        gradientLayer!.startPoint = CGPoint(x:0,y:0)
        gradientLayer!.endPoint = CGPoint(x:1,y:0)
        let fromColor = beginColor.cgColor
        let toColor = endColor.cgColor
        gradientLayer!.colors = [fromColor,toColor]
        if !find{
            target.layer.addSublayer(gradientLayer!)
        }
    }
    
    // 渐变
     dynamic public class func gradient(_ target:UIView,colors:[Any])
     {
         var find=false
         var gradientLayer:CAGradientLayer?
         if let sublayers = target.layer.sublayers{
             for layer in sublayers{
                 if let temp=layer as? CAGradientLayer{
                     gradientLayer = temp
                     find=true
                     break
                 }
             }
         }
         if gradientLayer == nil{
             gradientLayer = CAGradientLayer()
         }
         gradientLayer!.frame = target.bounds
         gradientLayer!.startPoint = CGPoint(x:0,y:0)
         gradientLayer!.endPoint = CGPoint(x:0,y:1)
         gradientLayer!.colors = colors 
         if !find{
             target.layer.addSublayer(gradientLayer!)
         }
     }
    
    // 渐变
    dynamic public class func gradient(_ target:UIView,startPoint:CGPoint,endPoint:CGPoint,beginColor:UIColor,endColor:UIColor)
    {
        var find=false
        var gradientLayer:CAGradientLayer?
        if let sublayers = target.layer.sublayers{
            for layer in sublayers{
                if let temp=layer as? CAGradientLayer{
                    gradientLayer = temp
                    find=true
                    break
                }
            }
        }
        if gradientLayer == nil{
            gradientLayer = CAGradientLayer()
        }
        target.layoutIfNeeded()
        gradientLayer!.frame = target.bounds
        gradientLayer!.startPoint = startPoint
        gradientLayer!.endPoint = endPoint
        let fromColor = beginColor.cgColor
        let toColor = endColor.cgColor
        gradientLayer!.colors = [fromColor,toColor]
        if !find{
            target.layer.addSublayer(gradientLayer!)
        }
    }
    
    dynamic public class func colorOf(_ hexColor:UInt32) -> UIColor
    {
        var alpha:CGFloat = CGFloat((hexColor & 0xFF000000) >> 24) / 255.0
        let red = CGFloat((hexColor & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((hexColor & 0xFF00) >> 8) / 255.0
        let blue = CGFloat(hexColor & 0xFF) / 255.0
        if(alpha<=0){
            alpha=1;
        }
        return UIColor.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    dynamic public class func colorOfString(_ hexString:String)->UIColor
    {
        let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        if hexString.hasPrefix("#") {
            scanner.scanLocation = 1
        }
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        return UIColor(red: red, green: green, blue: blue, alpha: 1)
    }
    dynamic public class func  RGBColor(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor {
        return UIColor.init(red: (r/255.0), green: (g/255.0), blue: (b/255.0), alpha: a)
    }
    
    dynamic public class func colorOfString(_ hexString:String,alpha:CGFloat)->UIColor
    {
        let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
        let scanner = Scanner(string: hexString)
        if hexString.hasPrefix("#") {
            scanner.scanLocation = 1
        }
        var color: UInt32 = 0
        scanner.scanHexInt32(&color)
        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask
        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }

    
    dynamic public class func colorOf(_ hexColor:UInt32,alpha:CGFloat) -> UIColor
    {
        let red = CGFloat((hexColor & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((hexColor & 0xFF00) >> 8) / 255.0
        let blue = CGFloat(hexColor & 0xFF) / 255.0
        return UIColor.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    // 获得行高
    dynamic public class func linesWith(_ label:UILabel) -> Int
    {
        label.layoutIfNeeded()
        let width = label.frame.size.width
        return linesWith(label,width:width)
    }
    // 获得行高
    dynamic public class func linesWith(_ label:UILabel,width:CGFloat) -> Int
    {
        let labelHeight = label.sizeThatFits(CGSize(width:width,height:CGFloat(MAXFLOAT))).height + 2;
        let lh=label.font.lineHeight;
        let count = floor(labelHeight/lh);
        return Int(count);
    }
    // 调整行间距
    dynamic public class func adjustLineSpace(_ label:UILabel,lineSpace:CGFloat)
    {
        label.layoutIfNeeded()
        var width = label.frame.size.width
        if width<1{
            width=SFitUtil.screenWidth-SFitUtil.fit(30)
        }
        label.preferredMaxLayoutWidth=width
        adjustLineSpace(label, width: width, lineSpace: lineSpace)
    }
    // 调整行间距 指定宽度
    dynamic public class func adjustLineSpace(_ label:UILabel,width:CGFloat,lineSpace:CGFloat=8)
    {
        let lines = SUIUtil.linesWith(label,width:width);
        // 单行不调整行间距
        if(lines<2){
            return
        }
        guard let text = label.text else{
            return
        }
        let range=NSMakeRange(0,text.count)
        var attributedString:NSMutableAttributedString
        if let temp = label.attributedText{
            attributedString = NSMutableAttributedString(attributedString: temp)
        }else{
            attributedString = NSMutableAttributedString(string:text)
        }
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.maximumLineHeight = label.font.pointSize
        paragraphStyle.minimumLineHeight = label.font.pointSize
        paragraphStyle.lineSpacing = SFitUtil.fit(lineSpace)-(label.font.lineHeight-label.font.pointSize)
        paragraphStyle.lineBreakMode = label.lineBreakMode
        paragraphStyle.alignment = label.textAlignment
        attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: range)
        let baselineOffset:CGFloat = (label.font.pointSize - label.font.lineHeight)/4
        attributedString.addAttribute(.baselineOffset, value: NSNumber(value: Float(baselineOffset)), range: range)
        label.attributedText = attributedString;
        label.sizeToFit()
    }
    
    dynamic public class func replaceAttributed(_ att: NSMutableAttributedString,key: String?,value: String?) -> NSMutableAttributedString
    {
        let range: NSRange? = (att.string as NSString?)?.range(of: key ?? "")
        if Int(range?.location ?? 0) == NSNotFound {
            return att
        }
        if let aRange = range {
            att.replaceCharacters(in: aRange, with: value ?? "")
        }
        return att
    }
    dynamic public class func replaceAttributed(_ att: NSMutableAttributedString,key: String?,value: String?,font:UIFont) -> NSMutableAttributedString
    {
        var range: NSRange? = (att.string as NSString?)?.range(of: key ?? "")
        if Int(range?.location ?? 0) == NSNotFound {
            return att
        }
        if let aRange = range {
            att.replaceCharacters(in: aRange, with: value ?? "")
        }
        range?.length = (value?.count ?? 0)
        att.addAttribute(.font, value:font, range: range!)
        return att
    }
    dynamic public class func replaceAttributed(_ att: NSMutableAttributedString,key: String?,value: String?,color:UIColor) -> NSMutableAttributedString
    {
        var range: NSRange? = (att.string as NSString?)?.range(of: key ?? "")
        if Int(range?.location ?? 0) == NSNotFound {
            return att
        }
        if let aRange = range {
            att.replaceCharacters(in: aRange, with: value ?? "")
        }
        range?.length = (value?.count ?? 0)
        att.addAttribute(.foregroundColor, value:color, range: range!)
        return att
    }
    
    dynamic public class func replaceAttributed(_ att: NSMutableAttributedString,key: String?,boldFontSize:CGFloat) -> NSMutableAttributedString
    {
        let range: NSRange? = (att.string as NSString?)?.range(of: key ?? "")
        if Int(range?.location ?? 0) == NSNotFound {
            return att
        }
        att.addAttribute(.font, value:SFitUtil.fitBoldFont(boldFontSize), range: range!)
        return att
    }
    dynamic public class func replaceAttributed(_ att: NSMutableAttributedString,key: String?,value: String?,fontSize: CGFloat) -> NSMutableAttributedString
    {
        var range: NSRange? = (att.string as NSString?)?.range(of: key ?? "")
        if Int(range?.location ?? 0) == NSNotFound {
            return att
        }
        if let aRange = range {
            att.replaceCharacters(in: aRange, with: value ?? "")
        }
        range?.length = (value?.count ?? 0)
        att.addAttribute(.font, value:SFitUtil.fitFont(fontSize), range: range!)
        return att
    }
    dynamic public class func replaceAttributed(_ att: NSMutableAttributedString,key: String?,value: String?,boldFontSize: CGFloat) -> NSMutableAttributedString
    {
        var range: NSRange? = (att.string as NSString?)?.range(of: key ?? "")
        if Int(range?.location ?? 0) == NSNotFound {
            return att
        }
        if let aRange = range {
            att.replaceCharacters(in: aRange, with: value ?? "")
        }
        range?.length = (value?.count ?? 0)
        att.addAttribute(.font, value:SFitUtil.fitBoldFont(boldFontSize), range: range!)
        return att
    }
    dynamic public class func replaceAttributed(_ att: NSMutableAttributedString,key: String?,value: String?,font: UIFont?,color:UIColor) -> NSMutableAttributedString
    {
        var range: NSRange? = (att.string as NSString?)?.range(of: key ?? "")
        if Int(range?.location ?? 0) == NSNotFound {
            return att
        }
        if let aRange = range {
            att.replaceCharacters(in: aRange, with: value ?? "")
        }
        range?.length = (value?.count ?? 0)
        att.addAttribute(.font, value:font!, range: range!)
        att.addAttribute(.foregroundColor, value:color, range: range!)
        return att
    }
    
    dynamic public class func scrollToTop(_ tableView:UITableView)
    {
        tableView.scrollToRow(at:IndexPath(row: 0, section: 0), at: .top, animated: false)
    }
    
    dynamic public class func changeButton(_ target:UIButton,icon:String)
    {
        target.setImage(UIImage.init(named: icon), for: .normal)
        target.setImage(UIImage.init(named: icon), for: .highlighted)
    }
    
    dynamic public class func placeTextField(_ target:UITextField,text:String,color:UIColor =  .lightGray)
    {
        if text.isEmpty{
            return
        }
        let placeholderAtt:[NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor : color,NSAttributedString.Key.font : target.font!]
        target.attributedPlaceholder=NSAttributedString(string: text,attributes: placeholderAtt)
    }
    // 设置锁屏
    dynamic public class func lockScreen(_ isLock:Bool){
        UIApplication.shared.isIdleTimerDisabled = isLock
    }
    // 获得cell布局后的高度
    dynamic public class func cellHeight(_ cell: UITableViewCell?) -> CGFloat {
        cell?.contentView.layoutIfNeeded()
        var h: CGFloat? = cell?.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        if h == 0 {
            h = 44
        }
        return h ?? 0.0
    }
    
    dynamic public class func changeColor(_ text: String, range: NSRange, color: UIColor, font: UIFont) -> NSMutableAttributedString?
    {
        if text.isEmpty{
            return nil
        }
        var temp = range
        if temp.location != NSNotFound {
            let attString = NSMutableAttributedString(string: text)
            temp.location = SDataUtil.clamp(text.count-1, min:0, max:temp.location)
            temp.length = SDataUtil.clamp(text.count,min:0,max:temp.location+temp.length) - temp.location
            //修改部分字体颜色
            attString.addAttribute(.foregroundColor, value: color, range: temp)
            attString.addAttribute(.font, value: font, range: range)
            return attString
        }
        return nil
    }
    dynamic public class func change(_ target:UILabel, range: NSRange,boldFontSize:CGFloat)
    {
        guard let text=target.text else{
            return
        }
        if text.isEmpty{
            return
        }
        var temp = range
        if temp.location == NSNotFound {
            return
        }
        let attString = NSMutableAttributedString(string: text)
        temp.location = SDataUtil.clamp(text.count-1, min:0, max:temp.location)
        temp.length = SDataUtil.clamp(text.count,min:0,max:temp.location+temp.length) - temp.location
        attString.addAttribute(.font, value: SFitUtil.fitBoldFont(boldFontSize), range: range)
        target.attributedText=attString
    }
    class func rotation(_ target:UIView){
        target.width = ScreenWidth
        target.height = ScreenHeight
        target.center = CGPoint(x:ScreenWidth/2,y:ScreenHeight/2)
        target.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
        target.layoutIfNeeded()
    }
    dynamic public class func shadow(_ target:UILabel,color:UIColor,radius:CGFloat,offset:CGSize){
        let text = target.text ?? ""
        let attrString = NSMutableAttributedString(string:text)
        let shadow = NSShadow()
        shadow.shadowColor = color
        shadow.shadowBlurRadius = radius
        shadow.shadowOffset = offset
        let attr: [NSAttributedString.Key : Any] = [.shadow: shadow]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        target.attributedText = attrString
    }
    
    dynamic public class func viewShadow(_ target:UIView,color:UIColor,radius:CGFloat,offset:CGSize)
    {
        target.layer.shadowColor = color.cgColor
        target.layer.shadowRadius = radius
        target.layer.shadowOffset = offset
        target.layer.shadowOpacity = 1
    }
    
    dynamic public class func snap(_ view:UIView)->UIImage
    {
        view.layoutIfNeeded()
        let rect=view.bounds.size
        UIGraphicsBeginImageContextWithOptions(rect,false,0)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    dynamic public class func dashLine(_ lineView:UIView,strokeColor: UIColor, lineWidth: CGFloat = 1, lineLength: Int = 4, lineSpacing: Int = 4)
    {
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = lineView.bounds
        shapeLayer.anchorPoint=CGPoint.zero
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [NSNumber(value: lineLength), NSNumber(value: lineSpacing)]
        
        let path = CGMutablePath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: lineView.frame.width, y: 0))
        shapeLayer.path = path
        lineView.backgroundColor = UIColor.clear
        lineView.layer.addSublayer(shapeLayer)
    }
    // 部分圆角
    dynamic public class func corner(_ view:UIView,corner:UIRectCorner,radii:CGSize)
    {
        view.layoutIfNeeded()
        let path=UIBezierPath.init(roundedRect: view.bounds, byRoundingCorners: corner,cornerRadii: radii)
        let layer=CAShapeLayer.init()
        layer.frame=view.bounds
        layer.path=path.cgPath
        view.layer.mask=layer
    }
    // 重置图片尺寸
    dynamic public class func resizeImage(_ target:UIImage?,width:CGFloat)->UIImage?
    {
        if target == nil{
            return nil
        }
        let h=width/target!.size.width*target!.size.height
        UIGraphicsBeginImageContext(CGSize(width:width,height:h))
        target?.draw(in: CGRect(x:0,y:0,width:width,height: h))
        let result=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return result
    }
    // 是否在指定的视图内
    dynamic public class func atView(_ view:UIView?,parent:UIView)->Bool
    {
        if view==nil{
            return false
        }
        if view!==parent{
            return true
        }
        var temp=view!.superview
        while temp != nil{
            if temp! == parent{
                return true
            }
            temp=temp!.superview
        }
        return false
    }
}
